<template>
	<view>
		<view>
			<view v-for="(message,index) in messages" :key="index" 
			style="position: relative;height: 60rpx;">
				<view :class="message.username == username?'r':'l'">
					{{message.message}}
				</view>
			</view>
		</view>
		<view style="position: fixed;bottom: 0;left: 0;z-index: 999;width: 100%;">
			<u--textarea 
			v-model="msg" placeholder="请输入内容" count autoHeight
			height="40" maxlength="300" :fixed="true"></u--textarea>
			<button style="" @click="sendMessage()">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				username: '',
				friendUsername: '',
				conversationId: -1,
				messages: [],
				message: {},
				msg: ''
			}
		},
		onLoad(option) {
			this.friendUsername = option.friendUsername
			this.conversationId = option.conversationId
			// console.log(this.conversationId)
			// console.log(this.friendUsername)
			uni.setNavigationBarTitle({
				title: this.friendUsername
			})
			uni.getStorage({
				key: 'username',
				success: (res) => {
					this.username = res.data
					// console.log(this.username)
				}
			})
			// console.log(this.username)
			this.webSocketConnect()
			// this.getMessages()
		},
		onShow() {
			console.log('显示页面')
			// this.webSocketConnect()
		},
		onBackPress() {
			console.log('隐藏页面')
			uni.closeSocket()
		},
		methods: {
			webSocketConnect() {
				uni.connectSocket({
					url: 'ws://10.152.174.195/im_api/sendMsg/' + this.username,
					success: () => {
						console.log('连接成功')
					}
				})
				uni.onSocketOpen(() => {
					console.log('lianjie')
				})
				uni.onSocketMessage((res) => {
					
					this.messages.push(JSON.parse(res.data))
					console.log('收到服务器内容：' + res.data)
				})
			},
			sendMessage() {
				this.message.username = this.username
				this.message.conversationId = this.conversationId
				this.message.message = this.msg
				uni.sendSocketMessage({
					data: JSON.stringify(this.message),
					success: () => {
						// this.messages.push(this.message)
						// this.msg = ''
					}
				})
				let message = new Object()
				message.username = this.message.username
				message.conversationId = this.message.conversationId
				message.message = this.message.message
				// console.log(message)
				this.messages.push(message)
				this.msg = ''
			},
			getMessages() {
				uni.request({
					url: 'http://10.152.174.195/message/getMessages/' + this.conversationId,
					success: (res) => {
						this.messages = res.data
						// console.log(this.conversations)
					}
				})
			},
		}
	}
</script>

<style>
	.r {
		position: absolute;
		right: 50rpx;
		/* height: 30rpx; */
		background-color: #00aaff;
		padding: 10rpx;
	}
	.l {
		position: absolute;
		left: 50rpx;
		/* height: 30rpx; */
		background-color: #55ff7f;
		padding: 10rpx;
	}
</style>
